package com.ruoyi.result.horizontalProjects.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.result.horizontalProjects.domain.ResultHorizontalProjects;
import com.ruoyi.result.horizontalProjects.domain.dto.ResultHorizontalProjectsDTO;
import com.ruoyi.result.horizontalProjects.domain.vo.ResultHorizontalProjectsVO;
import com.ruoyi.result.horizontalProjects.mapper.ResultHorizontalProjectsMapper;
import com.ruoyi.result.horizontalProjects.service.IResultHorizontalProjectsService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.team.trash.domain.AchievementTrash;
import com.ruoyi.team.trash.mapper.AchievementTrashMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 横向课题Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-22
 */
@Service
public class ResultHorizontalProjectsServiceImpl implements IResultHorizontalProjectsService
{
    @Autowired
    private ResultHorizontalProjectsMapper resultHorizontalProjectsMapper;

    @Autowired
    private SysUserPostMapper sysUserPostMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private AchievementTrashMapper achievementTrashMapper;
    /**
     * 查询横向课题
     *
     * @param id 横向课题主键
     * @return 横向课题
     */
    @Override
    public ResultHorizontalProjects selectResultHorizontalProjectsById(Long id)
    {
        return resultHorizontalProjectsMapper.selectResultHorizontalProjectsById(id);
    }
    @Override
    public List<ResultHorizontalProjectsVO> selectResultHorizontalProjectsByIds(Long[] ids) {
        if (ids == null || ids.length == 0) {
            return Collections.emptyList();
        }
        List<ResultHorizontalProjects> resultHorizontalProjectsList = resultHorizontalProjectsMapper.selectResultHorizontalProjectsByIds(ids);
        List<ResultHorizontalProjectsVO> resultHorizontalProjectsVOList = new ArrayList<>();

        for (ResultHorizontalProjects resultPaper : resultHorizontalProjectsList) {
            ResultHorizontalProjectsVO resultHorizontalProjectsVO = new ResultHorizontalProjectsVO();
            // 假设 resultHorizontalProjects 和 resultHorizontalProjectsVO 有相同的字段，先进行复制
            BeanUtils.copyProperties(resultPaper, resultHorizontalProjectsVO);

            // 根据 userId 查询 nick_name
            SysUser sysUser = sysUserMapper.selectUserById(resultPaper.getUserId());
            resultHorizontalProjectsVO.setNickName(sysUser.getNickName());

            resultHorizontalProjectsVOList.add(resultHorizontalProjectsVO);
        }
        return resultHorizontalProjectsVOList;
    }

    /**
     * 查询横向课题列表
     *
     * @param dto 横向课题DTO
     * @return TableDataInfo 表格数据
     */
    @Override
    public TableDataInfo selectResultHorizontalProjectsList(ResultHorizontalProjectsDTO dto) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long deptId = loginUser.getUser().getDeptId();

        // 判断是否为超级管理员（若依默认超级管理员用户ID为1）
        boolean isSuperAdmin = loginUser.getUser().getUserId().equals(1L);

        // 非超级管理员才进行部门过滤
        if (!isSuperAdmin) {
            dto.setDeptId(deptId);
        }

        // 分页参数
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotNull(pageDomain.getPageNum()) && StringUtils.isNotNull(pageDomain.getPageSize())) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageDomain.getPageNum(), pageDomain.getPageSize(), orderBy)
                    .setReasonable(pageDomain.getReasonable());
        }

        // 查询横向课题列表
        List<ResultHorizontalProjects> list = resultHorizontalProjectsMapper.selectResultHorizontalProjectsList(dto);

        // 转换为VO并填充用户昵称
        List<ResultHorizontalProjectsVO> voList = list.stream().map(r -> {
            ResultHorizontalProjectsVO vo = new ResultHorizontalProjectsVO();
            BeanUtils.copyProperties(r, vo);
            if (r.getUserId() != null) {
                SysUser sysUser = sysUserMapper.selectUserById(r.getUserId());
                if (sysUser != null) {
                    vo.setNickName(sysUser.getNickName());
                }
            }
            return vo;
        }).collect(Collectors.toList());

        // 返回表格数据
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        rspData.setRows(voList);
        return rspData;
    }

    /**
     * 新增横向课题
     *
     * @param resultHorizontalProjects 横向课题
     * @return 结果
     */
    @Override
    public int insertResultHorizontalProjects(ResultHorizontalProjects resultHorizontalProjects)
    {
        return resultHorizontalProjectsMapper.insertResultHorizontalProjects(resultHorizontalProjects);
    }

    /**
     * 修改横向课题
     *
     * @param resultHorizontalProjects 横向课题
     * @return 结果
     */
    @Override
    public int updateResultHorizontalProjects(ResultHorizontalProjects resultHorizontalProjects)
    {
        return resultHorizontalProjectsMapper.updateResultHorizontalProjects(resultHorizontalProjects);
    }

    /**
     * 批量删除横向课题
     *
     * @param ids 需要删除的横向课题主键
     * @return 结果
     */
    @Override
    public int deleteResultHorizontalProjectsByIds(Long[] ids)
    {
        List<ResultHorizontalProjects> resultHorizontalProjectsList = resultHorizontalProjectsMapper.selectResultHorizontalProjectsByIds(ids);
        for (ResultHorizontalProjects resultHorizontalProjects : resultHorizontalProjectsList) {
            AchievementTrash achievementTrash = new AchievementTrash();
            achievementTrash.setUserid(resultHorizontalProjects.getUserId());
            achievementTrash.setAchievementType("横向课题");
            achievementTrash.setTitle(resultHorizontalProjects.getProjectName());
            achievementTrash.setAchievementId(resultHorizontalProjects.getId());
            achievementTrash.setDeletedAt(new Date());
            achievementTrashMapper.insertAchievementTrash(achievementTrash);
        }
        return resultHorizontalProjectsMapper.deleteResultHorizontalProjectsByIds(ids);
    }

    /**
     * 删除横向课题信息
     *
     * @param id 横向课题主键
     * @return 结果
     */
    @Override
    public int deleteResultHorizontalProjectsById(Long id)
    {
        return resultHorizontalProjectsMapper.deleteResultHorizontalProjectsById(id);
    }
}
